package com.ego.dubbo.service.impl;

import com.ego.commons.exception.DaoException;
import com.ego.dubbo.service.TbItemDubboService;
import com.ego.mapper.TbItemDescMapper;
import com.ego.mapper.TbItemMapper;
import com.ego.pojo.TbItem;
import com.ego.pojo.TbItemDesc;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
// 此注解是将实现类放置到zookeeper中
@Service
public class TbItemDubboServiceImpl implements TbItemDubboService {
    @Autowired
    private TbItemMapper tbItemMapper;
    @Autowired
    private TbItemDescMapper tbItemDescMapper;
    @Override
    public List<TbItem> selectByPage(int pageSize, int pageNumber) {
        // 分页插件放置第一行,必须放置在查询语句前，否则无效
        PageHelper.startPage(pageNumber,pageSize);
        // 进行查询
        List<TbItem> tbItems = tbItemMapper.selectByExample(null);
        // 不要忘记PageInfo构造方法参数
        PageInfo<TbItem> pageInfo = new PageInfo<>(tbItems);

        return pageInfo.getList();
    }

    @Override
    public long selectCount() {
        return tbItemMapper.countByExample(null);
    }

    @Override
    // 监测异常，当有异常时会进行事务回滚,声明式事务注解
    @Transactional
    public int updateStatusByIds(long[] ids, byte status) throws DaoException{
        int index = 0;
        for (long id : ids) {
            TbItem tbItem = new TbItem();
            tbItem.setId(id);
            tbItem.setStatus(status);
            // 保证批量修改时间相同
            tbItem.setUpdated(new Date());
            index += tbItemMapper.updateByPrimaryKeySelective(tbItem);
        }
        // 如何判断是否批量修改成功？
        // 根据索引数 = ids[] 数组的长度
        if (index == ids.length){
            return 1;
        }
        // 如果失败，需要事务回滚（1.抛出自定义异常2.方法抛出异常3.添加注解Transaction，监听异常从而做出回滚操作）
        throw new DaoException("修改失败");
    }

    @Override
    @Transactional
    public int insertItem(TbItem tbItem, TbItemDesc tbItemDesc) {
        try {
            int index = tbItemMapper.insert(tbItem);
            if(index==1){
                int index2 = tbItemDescMapper.insert(tbItemDesc);
                if (index2==1){
                    return 1;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        throw new DaoException("新增失败");
    }

    @Override
    @Transactional
    public int update(TbItem tbItem, TbItemDesc tbItemDesc) throws DaoException{
        try {
            int index1 = tbItemMapper.updateByPrimaryKeySelective(tbItem);
            if(index1==1){
                int index2 = tbItemDescMapper.updateByPrimaryKeySelective(tbItemDesc);
                if(index2==1){
                    return 1;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        throw new DaoException("更新失败");
    }
}
